/**
 *  @author Ion Morozan
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.dddforandroid.database.local;

import java.lang.reflect.Type;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.impl.client.DefaultHttpClient;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;

import com.dddforandroid.database.server.NotePad.Notes;
import com.dddforandroid.database.server.SyncServerDatabase;
import com.dddforandroid.design.CurrentTasksActivity;
import com.dddforandroid.design.TasksArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

public class ReadNote extends
		AsyncTask<DefaultHttpClient, Integer, ArrayList<Notes>> {

	private static final String noNotes = "No notes available!";
	/* The Context of the application */
	Context mainActivity;
	/* The ServerDatabase object, used for synchronizing the server database */
	private SyncServerDatabase nosql;

	DefaultHttpClient authClient;

	String serverDB;

	ListView list;

	public static String email;
	public static String userId;

	/**
	 * Constructor used for the CreateNote class
	 * 
	 * @param mainActivity
	 *            The Context of the application
	 * @param nosql
	 *            The ServerDatabase object
	 */
	public ReadNote(Context mainActivity, SyncServerDatabase nosql,
			ListView list) {
		this.mainActivity = mainActivity;
		this.nosql = nosql;
		this.list = list;
	}

	@Override
	protected ArrayList<Notes> doInBackground(DefaultHttpClient... client) {
		authClient = client[0];
		ArrayList<Notes> note = initializeLocalDatabase();

		return note;
	}

	/**
	 * Method called at the beginning of the program to synchronize the local
	 * and the server databases. 
	 */
	private ArrayList<Notes> initializeLocalDatabase() {
		ContentResolver provider = mainActivity.getContentResolver();
		provider.delete(Notes.CONTENT_URI, null, null);

		ArrayList<Notes> notes = new ArrayList<Notes>();

		/* Use the GET Method to access the data */
		serverDB = nosql.getData(authClient);

		if (serverDB.equals(noNotes))
			return null;

		GsonBuilder builder = new GsonBuilder();
		/** Register an adapter to manage the date types as long values */
		builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
			public Date deserialize(JsonElement json, Type arg1,
					JsonDeserializationContext arg2) throws JsonParseException {
				return new Date(json.getAsJsonPrimitive().getAsLong());
			}
		});
		Gson gson = builder.create();

		/* Convert the result in a list of Notes */
		Type collectionType = new TypeToken<ArrayList<Notes>>() {
		}.getType();
		notes = gson.fromJson(serverDB, collectionType);

		ContentValues mValues = new ContentValues();
		for (Notes note : notes) {
			mValues.put(Notes._ID, note.getId());
			mValues.put(Notes.TITLE, note.getTitle());
			mValues.put(Notes.NOTE, note.getNote());

			long date_str = note.getCreatedDate();

			mValues.put(Notes.CREATED_DATE, date_str);
			provider.insert(Notes.CONTENT_URI, mValues);

		}

		return notes;
	}

	@Override
	protected void onPostExecute(ArrayList<Notes> notes) {

		if (notes != null) {
			String[] showNote = new String[notes.size()];
			int count = 0;
			for (Notes note : notes) {
				long date_long = note.getCreatedDate();

				Date date = new Date(date_long);
				int year, month, day;
				day = date.getDate();
				month = date.getMonth();
				year = date.getYear() + 1900;

				String monthName = new DateFormatSymbols().getMonths()[month];

				showNote[count++] = note.getTitle() + " - " + day + "-"
						+ monthName.substring(0, 3) + "-" + year;
			}
			list.setAdapter(new TasksArrayAdapter(mainActivity, showNote,
					notes, nosql));
		} else {
			list.setAdapter(null);
		}

		CurrentTasksActivity.sync.setClickable(true);
		CurrentTasksActivity.progress.dismiss();
	}
}
